<template>
  <div class="base">
    <div style="width: 524px; margin: auto">
      <common-form :form="form"
                   ref="form"
                   class="form"
                   :formData="formData"
                   labelWidth="110px"
                   :rules="rules">
        <!--提示-->
        <div slot="ctime" class="prompt">
          {{$t('configLazyLoad.businessConfig.businessTip')}}
          {{$t('configLazyLoad.businessConfig.businessTip1')}}
          {{maxTime.show}}
        </div>
        <div slot="showFields" class="prompt">
          {{$t('configLazyLoad.businessConfig.businessTip2')}}
          <el-popover
            placement="bottom-start"
            width="338"
            trigger="click"
          >
            <img style="width:338px" src="../../../../../assets/img/configBusiness/fields-example@2x.png" alt="">
            <div class="prompt">{{$t('configLazyLoad.businessConfig.businessTip3')}}</div>
            <el-button type="text" slot="reference">{{$t('configLazyLoad.businessConfig.displayEffect')}}</el-button>
          </el-popover>
        </div>
        <el-checkbox-group v-model="form.showFields"
                           class="flow-fields"
                           slot="showFieldsSlot"
                           size="mini">
          <el-checkbox v-for="item in flowFieldsArr"
                       v-if="firstStepFields.indexOf(item._id) !== -1"
                       :label="item._id"
                       style="margin: 0 10px 10px 0"
                       border>
            {{item.name}}
          </el-checkbox>
        </el-checkbox-group>
        <div slot="customerRequireSlot">
          <el-select  v-model="form.customerRequire"
                      style="width: 100%">
            <el-option
                      :label="$t('configLazyLoad.businessConfig.orderRequired')"
                      value="yes">
            </el-option>
            <el-option
                      :label="$t('configLazyLoad.businessConfig.orderNotRequired')"
                      value="no">
            </el-option>
          </el-select>
        </div>
        <div slot="notifySlot">
          <el-select  v-model="form.notify.type"
                      :placeholder="$t('configLazyLoad.businessConfig.informWay')"
                      style="width: 100%">
            <el-option
                      :label="$t('configLazyLoad.businessConfig.none')"
                      value="no">
            </el-option>
            <el-option
                      :label="$t('public.SMS')"
                      value="sms">
            </el-option>
          </el-select><br>
          <el-select v-model="form.notify.notifyType"
                      :placeholder="$t('configLazyLoad.businessConfig.selectInformWay')"
                     style="width: 100%">
            <el-option
                      :label="$t('configLazyLoad.businessConfig.businessTransferNotice')"
                      value="businessTransfer">
            </el-option>
          </el-select><br>
          <el-select v-model="form.notify.smsTemplate.templateId"
                     :placeholder="$t('configLazyLoad.businessConfig.selectTemplate')"
                     style="width: 100%">
              <el-option
                v-for="item in smsTemplate"
                :key="item._id"
                :label="item.name"
                :value="item._id">
              </el-option>
          </el-select>
          <div class="content">
          {{smsTemp.content || $t('configLazyLoad.businessConfig.selectTemplateShow')}}
          </div>
          <m7-select v-model="form.notify.failureNotify" :options="allAgent" :placeholder="$t('configLazyLoad.businessConfig.sendFailureAlertPerson')" :multiple="true" :filterable="true">
          </m7-select>
          <div class="prompt">{{$t('configLazyLoad.businessConfig.businessTip4')}}</div>
        </div>
        <el-button class="primary_btn"
                   type="primary"
                   size="mini"
                   slot="button"
                   v-if="busType !== 'newFlow'"
                   @click.stop="update">{{$t('public.save')}}</el-button>
      </common-form>
    </div>
  </div>
</template>

<script>
  import commonForm from '../base/commonForm'
  import {deepClone} from '@/utils/m7Utils'
  import {parseIntTime, timeTrans} from '@/utils/workflowUtils'
  import {checkform} from '@/utils/validate'
  const baseForm = {
    name: '',
    customerRequire: 'yes',
    tips: '',
    ctype: '',
    ctime: '',
    showFields: [],
    urgeTime:'',
    urgeType:'',
    notify: {
      type: '',
      notifyType: '',
      failureNotify: [],
      smsTemplate: {templateId: ''}
    }
  }
  export default {
    name: 'base-info',
    props: {
    },
    inject: ['busType'],
    data () {
      let self = this
      let validate1 = (rule, value, callback) => {
        if (checkform(value, 'Number5')) {
          callback(new Error(this.$t('configLazyLoad.businessConfig.mustBePositiveInteger')))
        } else if (self.maxTime.seconds > parseIntTime(self.form.ctype, self.form.ctime)) {
          callback(new Error(this.$t('configLazyLoad.businessConfig.mustBeGreaterThanOrEqual') + self.maxTime.show))
        } else {
          callback()
        }
      }
      let timeNumber = (rule, value, callback) => {
        if (checkform(value, 'Number5')) {
          callback(new Error(this.$t('configLazyLoad.businessConfig.mustBePositiveInteger')))
        } else if (value && (Number(value) <= 0 || Number(value) > 9999)) {
          callback(new Error(this.$t('configLazyLoad.businessConfig.mustBePositiveInteger1')))
        } else {
          callback()
        }
      }
      return {
        form: deepClone(baseForm),
        formData: [
        ],
        rules: {
          name: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (value.length > 10) {
                  callback(new Error(this.$t('configLazyLoad.businessConfig.nameTip')))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          ctime: [
            {required: false, validator: validate1, trigger: 'blur'}
          ],
          urgeTime: [
            {required: false, validator: timeNumber, trigger: 'blur'}
          ],
        },
        maxTime: {show: '', seconds: 0},
        smsTemplate: [],
        smsSign: [],
        allAgent: []
      }
    },
    computed: {
      // 开始步骤
      firstStep () {
        let steps = this.$store.state.config.businessConfig[this.busType].flowSteps || []
        return steps.filter((item) => item.isBegin)[0] || {}
      },
      smsTemp () {
        let tmpl = this.smsTemplate.filter((item) => {
          return item._id === this.form.notify.smsTemplate.templateId
        })[0] || {}
        return Object.assign({}, tmpl)
      },
      // 开始步骤的字段
      firstStepFields () {
        let stepFields = this.firstStep.stepFields || []
        let arr = []
        stepFields.forEach((item) => {
          let cols = item.cols || []
          cols.forEach((one) => {
            (one.fields || []).forEach((field) => {
              arr.push(field._id)
            })
          })
        })
        return arr
      },
      // 工单全部字段
      flowFieldsArr () {
        return this.$store.state.config.businessConfig[this.busType].allFields || []
      }
    },
    components: {
      commonForm
    },
    methods: {
      create () {
        let data = this.$refs.form.submit()
        return data
      },
      close () {},
      // 筛选出步骤中，时限最长的
      maxStepTime () {
        let max = 0
        let maxIndex = null
        let flowSteps = this.$store.state.config.businessConfig[this.busType].flowSteps
        flowSteps.forEach((item, index) => {
          if (item.ctype && item.ctime) {
            let time = parseIntTime(item.ctype, item.ctime)
            if (time > max) {
              maxIndex = index
              max = time
            }
          }
        })
        let obj = {seconds: max, show: ''}
        if (maxIndex !== null) {
          let maxStep = flowSteps[maxIndex]
          obj.show = timeTrans(maxStep.ctype, maxStep.ctime)
        }
        return obj
      },
      // 回显
      initData () {
        this.$refs.form.clearValidate()
        let {name, ctype, ctime, customerRequire, tips, _id, showFields,urgeTime,urgeType, notify} = this.$store.state.config.businessConfig[this.busType].flowInfo
        showFields = deepClone(showFields) || []
        notify = deepClone(notify || baseForm.notify)
        if (customerRequire === undefined) customerRequire = 'yes'
        this.form = {name, ctype, ctime, customerRequire, tips, _id, showFields, urgeTime,urgeType, notify}
        this.templateChange()
        this.maxTime = this.maxStepTime()
        if (!this.form.ctype) {
          this.form.ctype = 'min'
        }
        if (!this.form.urgeType) {
          this.form.urgeType = 'min'
        }
      },
      reset () {
        this.form = deepClone(baseForm)
        this.form.ctype = 'min'
        this.form.urgeType = 'min'
      },
      // 保存
      update () {
        let data = this.$refs.form.submit()
        if (data.success) {
          if (this.form.notify.type === 'sms') {
            if (!this.form.notify.smsTemplate.templateId) {
              return this.$message.error(this.$t('configLazyLoad.businessConfig.selectSmsTemplate'))
            }
            if (!this.form.notify.notifyType) {
              return this.$message.error(this.$t('configLazyLoad.businessConfig.selectInformWay'))
            }
            let sms = {template: this.smsTemp.content, smsChannel: this.smsTemp.smsChannel[0]}
            for (let j = 0; j < this.smsSign.length; j++) {
              if (this.smsTemp.sign === this.smsSign[j]._id) {
                sms.templateSign = this.smsSign[j].subcode + '_' + this.smsSign[j].name
              }
            }
            Object.assign(data.data.notify.smsTemplate, sms)
          }
          // 更新前过滤掉不是开始步骤的字段
          data.data.showFields = data.data.showFields.filter((_id) => this.firstStepFields.indexOf(_id) !== -1)
          if (this.form.notify.type === 'sms') {
            // 短信收费提醒
            this.$confirm(this.$t('configLazyLoad.businessConfig.businessTip5'), this.$t('public.tip'), {
              confirmButtonText: this.$t('public.confirm'),
              cancelButtonText: this.$t('public.cancel'),
              type: 'warning'
            }).then(() => {
              this.$store.dispatch('updateBusinessFlowInfo', data.data).then((res) => {
                if (res.success) {
                  this.$message.success(this.$t('monitor.saveSuccess'))
                  this.$store.commit('flowConfig/UPDATE_FLOW_INFO', {type: 'update', data: res.data})
                }
              })
            })
          } else {
            this.$store.dispatch('updateBusinessFlowInfo', data.data).then((res) => {
              if (res.success) {
                this.$message.success(this.$t('monitor.saveSuccess'))
                this.$store.commit('flowConfig/UPDATE_FLOW_INFO', {type: 'update', data: res.data})
              }
            })
          }
        }
      },
      templateChange () {
        let smsTemplate = this.form.notify.smsTemplate
        let isHas = this.smsTemplate.some((item) => {
          if (item._id === smsTemplate.templateId) {
            return true
          }
        })
        if (smsTemplate.templateId && !isHas) {
          this.$message.error(this.$t('configLazyLoad.businessConfig.businessTip6'))
          smsTemplate.templateId = ''
        }
      },
      radioChange(val,type){
        if(type === 'ctype'){
          this.form.ctype = val
        } else {
          this.form.urgeType = val
        }
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'smsTemplate'}).then((res) => {
        this.smsTemplate = (res || []).filter((item) => item.type === 'flow')
        this.templateChange()
      })
      this.$store.dispatch('getCache', {type: 'smsSign'}).then((res) => {
        this.smsSign = res
      })
      this.allAgent = this.$getCache('agents').filter((item) => {
        return item.status === 'enable'
      }).map((item) => {
        return {value: item._id, label: `${item.displayName}[${item.exten}]`}
      })
      this.allAgent.unshift({value: 'creator', label: this.$t('business.businessCreate')}, {value: 'master', label: this.$t('business.preAgent')})
      let formData = [
          {label: this.$t('channelsettings.process2'), name: 'name', type: 'input'},
          {label: this.$t('configLazyLoad.businessConfig.customerRequire'), name: 'customerRequire', type: 'slot'},
          {label: this.$t('configLazyLoad.businessConfig.totalTimeLimit'), name: 'ctime', type: 'timeOut', time: 'ctype'}
      ]
      // 工单详情页有'列表卡片展示字段'
      if (this.busType === 'detailFlow') {
        formData.push({label: this.$t('configLazyLoad.businessConfig.businessRemind'), name: 'notify', type: 'slot'},{label: this.$t('configLazyLoad.businessConfig.cuiBanInterval'), name: 'urgeTime',time: 'urgeType', type: 'timeOut'}, {label: this.$t('configLazyLoad.businessConfig.listCardDisplayField'), name: 'showFields', type: 'slot'})
      }
      this.formData = formData
    }
  }
</script>

<style scoped lang='stylus'>
  @import '../../../../../assets/common.styl'
  .base
    padding 20px 0
    box-sizing border-box
    display flex
    .flow-fields
      padding 8px 8px 0
      margin-bottom 8px
      border-radius 3px
      min-height 40px
      border 1px solid $c-border1
      margin-top 10px
  .form
    width: 360px
  .prompt
    color $c-prompt
    font-size 12px
    line-height 16px
  .content
    padding 15px
    font-size 12px
    line-height 16px
    background-color $c-back
    border-radius 5px
</style>
